Java Switch Statement

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
In other words, the switch statement tests the equality of a variable against multiple values.

Points to Remember

Syntax:

switch(expression){

casevalue1:

//code to be executed;

break; //optional

casevalue2:

//code to be executed;

break; //optional

.......

default;

code to be executed if all cases are not matched;

}

Example:

SwitchExample.java

public classSwitchExample {

public static voidmain(String[] args) {

//Declaring a variable for switch expression

intnumber=20;

//Switch expression

switch(number){

//Case statements

case10: System.out.println("10")

break;

case20: System.out.println("20");

break;

case30: System.out.println("30");

break;

//Default case statement

default:System.out.println("Not in 10, 20 or 30");

}

}

}

Test it Now

Output:

20

Java Wrapper in Switch Statement

Java allows us to use four wrapper classes: Byte, Short, Integer and Long in switch statement.

Example:

WrapperInSwitchCaseExample.java

//Java Program to demonstrate the use of Wrapper class

//in switch statement

public class WrapperInSwitchCaseExample {

public static voidmain(String args[])

{

Integer age = 18;

switch(age)

{

case(16):

System.out.println("You are under 18.");

break;

case(18):

System.out.println("You are eligible for vote.");

break;

case

(65):

System.out.println("You are senior citizen.");

break;

default:

System.out.println("Please give the valid age.");

break;

}

}

}

Test it Now

Output:

You are eligible for vote.